<template>
  <!-- 输入框容器 -->
  <view>
    <!-- 输入区域容器 -->
    <view
      ref="inputContainer"
      class="footer-container hb-rounded-[44rpx] hb-p-2 hb-flex hb-items-center hb-bg-white hb-pr-0"
      :style="{
        'box-shadow': '0px 6px 12px 4px rgba(150, 151, 153, 0.16)',
        position: disabled ? 'static' : 'fixed',
        bottom: `${keyboardHeight}px`,
        left: '24rpx',
        right: '24rpx',
        'z-index': 100,
        transition: 'bottom 0s',
      }"
    >
      <!-- 信息来源选择器 -->
      <view
        v-if="showChatSource"
        class="hb-flex hb-items-center hb-bg-[#F2F3F5] hb-px-2 hb-py-1 hb-rounded-[44rpx] hb-mr-2.5"
        id="chat-guide-step-1"
        @click="showSourceMenu = true"
      >
        <tm-icon
          :name="sourceActions[selectedSource].icon"
          :fontSize="40"
          color="#2878FF"
        ></tm-icon>
        <tm-icon name="ali-icon icon-xia" :fontSize="24"></tm-icon>
      </view>

      <!-- 文本输入框 -->
      <view class="hb-flex-1 hb-min-h-7 hb-flex hb-items-center" @click="handleInputAreaClick">
        <textarea
          ref="textareaRef"
          v-model.trim="inputValue"
          class="hb-w-full hb-text-[28rpx]  hb-resize-none"
          :style="{
            minHeight: '40rpx',
            height: '40rpx',
            maxHeight: '600rpx',
          }"
          :disabled="disabled"
          :maxlength="99999"
          :auto-height="true"
          :adjust-position="false"
          :cursor-spacing="10"
          :placeholder="placeholder"
          :focus="isFocused"
          @keyboardheightchange="onKeyboardHeightChange"
          @linechange="onLineChange"
          @blur="onBlur"
          @focus="onFocus"
        ></textarea>
      </view>

      <view
        :class="[
          inputValue.trim() ? 'hb-bg-[#2878FF]' : 'hb-bg-[#CCCCCC]',
          lastMessage.typing ? 'icon-rotating' : '',
        ]"
        class="hb-flex hb-justify-end hb-pr-3 hb-pl-3 hb-h-7 hb-flex hb-items-center"
        @click="disabled ? handleInputAreaClick() : onSend()"
      >
        <tm-icon
          :name="lastMessage.typing ? 'ali-icon icon-zanting' : 'ali-icon icon-fasong'"
          :font-size="40"
          :color="inputValue.trim() || disabled ? '#2878FF' : ''"
        ></tm-icon>
      </view>
    </view>

    <!-- 信息来源底部操作菜单 -->
    <tm-action-menu
      :round="10"
      :list="sourceActions"
      v-model:model-value="showSourceMenu"
      v-model:active="selectedSource"
      @cancel="showSourceMenu = false"
      @change="handleSourceChange"
      title="选择信息来源"
      cancelText="取消"
      :hideCancel="false"
      :titleType="'text'"
    />
  </view>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick, onMounted, getCurrentInstance } from 'vue';
  import { debounce } from 'lodash-es';
  import { ChatSource } from '@/enums/MessageEnum';
  import { MessageRecord } from '@/api/aiChatPage/types';
  import { GuideType, useGuideStore } from '@/store/modules/guide';
  import { getCurrentRouteInfo } from '@/router';

  // 定义组件属性
  const props = defineProps({
    // 是否显示信息来源选择器
    showChatSource: {
      type: Boolean,
      default: true,
    },
    // 是否禁用输入和发送
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否自动获取焦点
    autoFocus: {
      type: Boolean,
      default: true,
    },
    circleUuid: {
      type: String,
      default: '',
    },
    circleName: {
      type: String,
    },
    chatSource: {
      type: String as PropType<ChatSource>,
      default: ChatSource.SHARE,
    },

    lastMessage: {
      type: Object as PropType<MessageRecord>,
      default: () => ({}),
    },
    inputContent: {
      type: String,
      default: '',
    },
  });

  // 定义信息来源项的类型接口
  interface SourceItem {
    text: string;
    id: ChatSource;
    icon?: string;
    color?: string;
    description?: string;
  }
  const emit = defineEmits<{
    (e: 'sourceChange', source: ChatSource): void;
    (e: 'updateFooterHeight', height: number): void;
    (e: 'updateInputContent', content: string): void;
    (e: 'cancel'): void;
    (e: 'send', content: string): void;
  }>();
  // const chatStore = useChatStore();

  // 组件内部状态
  const inputContainer = ref<any>(null);
  const textareaRef = ref<any>(null);
  const inputValue = ref('');
  const isFocused = ref(false);
  const instance = getCurrentInstance();
  const bottom = uni.upx2px(48);
  const keyboardHeight = ref(bottom); // 键盘高度

  // 信息来源菜单状态
  const showSourceMenu = ref(false);

  const placeholder = computed(() => {
    return '给超级助手发消息';
  });

  // 信息来源选项 - 适配tm-action-menu的数据结构
  const sourceActions = computed<SourceItem[]>(() => [
    {
      text: `问共享信息${props.circleName ? `(${props.circleName})` : '（好友+圈子+公开）'}`,
      id: ChatSource.SHARE,
      icon: 'ali-icon icon-wenquanzi',
      color: '#2878FF',
      description: '基于共享的资源提问，适用于寻找人脉、资源等',
    },

    {
      text: '问自己',
      id: ChatSource.PRIVATE,
      icon: 'ali-icon icon-wenziji',
      color: '#2878FF',
      description: '只基于您自己的知识库提问',
    },

    {
      text: '问全网（联网搜索）',
      id: ChatSource.PUBLIC,
      icon: 'ali-icon icon-wenquanwang',
      color: '#3498DB',
      description: '从全网搜索获取答案',
    },
  ]);

  // 当前选中的信息来源
  const selectedSource = ref(0);

  watch(
    () => props.inputContent,
    (val) => {
      inputValue.value = val;
    },
  );

  // 默认选中信息来源
  watch(
    () => props.chatSource,
    (val) => {
      if (val) {
        selectedSource.value = sourceActions.value.findIndex((item) => item.id === val);
      } else {
        selectedSource.value = 0;
      }
      emit('sourceChange', sourceActions.value[selectedSource.value].id);
    },
    {
      immediate: true,
    },
  );

  /**
   * 处理信息来源选择
   * @param val 选择的信息来源
   */
  const handleSourceChange = (val: any) => {
    emit('sourceChange', val.id as ChatSource);
  };

  /**
   * 处理输入区域点击
   * 如果组件处于禁用状态，则跳转到聊天界面
   */
  const handleInputAreaClick = () => {
    if (props.disabled) {
      navigateTo({
        name: 'aiChatPage',
        options: {
          circleUuid: props.circleUuid,
          circleName: props.circleName,
          chatSource: sourceActions.value[selectedSource.value].id,
        },
      });
    } else {
      setFocus();
    }
  };

  /**
   * 处理输入框失去焦点
   */
  const onBlur = () => {
    isFocused.value = false;
  };

  /**
   * 设置输入框焦点
   */
  const setFocus = () => {
    if (props.disabled) return;

    isFocused.value = true;
    // 某些平台可能需要额外处理
    nextTick(() => {
      // #ifdef APP-PLUS || H5 || MP-WEIXIN
      if (textareaRef.value) {
        textareaRef.value.focus();
      }
      // #endif
    });
  };

  /**
   * 监听键盘高度变化
   * @param e 键盘事件对象
   */
  const onKeyboardHeightChange = (e: any) => {
    if (props.disabled) return;

    const newKeyboardHeight = e.detail.height + bottom;
    // 如果键盘高度发生变化，重新计算总高度
    if (newKeyboardHeight !== keyboardHeight.value) {
      keyboardHeight.value = newKeyboardHeight;
      nextTick(() => {
        calculateHeight();
      });
    }
  };

  const onFocus = () => {
    console.log('onFocus');
  };
  /**
   * 计算并发送组件高度变化
   * 总高度 = 组件高度 + 键盘高度
   */
  const calculateHeight = () => {
    const query = uni.createSelectorQuery().in(instance?.proxy);
    query
      .select('.footer-container')
      .boundingClientRect((data: any) => {
        if (data) {
          const totalHeight = data.height + keyboardHeight.value;
          !props.disabled && emit('updateFooterHeight', totalHeight);
        }
      })
      .exec();
  };

  // 防抖处理的高度计算函数
  const debouncedCalculateHeight = debounce(calculateHeight, 10);

  /**
   * 监听输入框行数变化
   * 用于自适应输入框高度
   */
  const onLineChange = (e: any) => {
    nextTick(() => {
      debouncedCalculateHeight();
    });
  };

  // 组件挂载时初始化高度和焦点
  onMounted(() => {
    nextTick(() => {
      calculateHeight();

      // 如果设置了自动获取焦点且非禁用状态，则自动聚焦
      if (props.autoFocus && !props.disabled) {
        setTimeout(() => {
          setFocus();
        }, 100); // 延迟一点时间以确保组件完全渲染
      }
    });
  });

  // 监听输入框值变化，实现双向绑定
  watch(inputValue, (val) => {
    emit('updateInputContent', val);
  });

  /**
   * 发送消息处理
   * 如果正在处理消息，则取消当前查询
   * 如果有内容，则发送消息
   */
  const onSend = () => {
    if (props.disabled) return;

    if (props.lastMessage.typing) {
      emit('cancel');
      return;
    }
    if (!inputValue.value.trim()) return;

    // 发送消息，并传递当前选择的信息来源
    emit('send', inputValue.value);
  };

  if (getCurrentRouteInfo().routeName === 'aiChatPage') {
    const ins = getCurrentInstance();
    useGuideStore().addGuide(
      0,
      {
        title: '切换搜索源',
        description: '可切换搜索范围，让回答内容更贴近您的需求',
        nodeInfo: {
          selector: '#chat-guide-step-1',
          ins,
        },
      },
      GuideType.CHAT,
    );
  }
</script>

<style lang="scss" scoped>

  .icon-rotating {
    position: relative;
  }

  .icon-rotating::before {
    content: '';
    position: absolute;
    width: 60rpx;
    height: 60rpx;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
    border: 2rpx solid rgba(40, 120, 255, 0.2); /* 淡蓝色完整边框，从3px改为1px */
  }

  .icon-rotating::after {
    content: '';
    position: absolute;
    width: 60rpx;
    height: 60rpx;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) rotate(0deg);
    border-radius: 50%;
    border: 2rpx solid transparent; /* 从3px改为1px */
    border-top-color: #2878ff; /* 高亮部分 */
    border-right-color: transparent;
    border-bottom-color: transparent;
    border-left-color: transparent;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from {
      transform: translate(-50%, -50%) rotate(0deg);
    }
    to {
      transform: translate(-50%, -50%) rotate(360deg);
    }
  }
</style>
